package com.rwb.springboot.sell.service.impl;

import com.lly835.bestpay.enums.BestPayTypeEnum;
import com.lly835.bestpay.model.PayRequest;
import com.lly835.bestpay.model.PayResponse;
import com.lly835.bestpay.model.RefundRequest;
import com.lly835.bestpay.model.RefundResponse;
import com.lly835.bestpay.service.impl.BestPayServiceImpl;
import com.rwb.springboot.sell.dto.OrderDTO;
import com.rwb.springboot.sell.enums.ResultEnum;
import com.rwb.springboot.sell.exception.MallException;
import com.rwb.springboot.sell.service.OrderService;
import com.rwb.springboot.sell.service.PayService;
import com.rwb.springboot.sell.utils.JsonUtil;
import com.rwb.springboot.sell.utils.MathUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by ruwenbo on 2018/1/7.
 */
@Service("payService")
public class PayServiceImpl implements PayService{

    // 订单名称
    private static final String ORDER_NAME = "微信点餐订单";

    private static final Logger LOGGER = LoggerFactory.getLogger(PayServiceImpl.class);

    @Autowired
    private BestPayServiceImpl bestPayService;

    @Autowired
    private OrderService orderService;

    @Override
    public PayResponse create(OrderDTO orderDTO) {
        PayRequest request = new PayRequest();
        request.setOpenid(orderDTO.getBuyerOpenid());
        request.setOrderAmount(orderDTO.getOrderAmount().doubleValue());
        request.setOrderId(orderDTO.getOrderId());
        request.setOrderName(ORDER_NAME);
        request.setPayTypeEnum(BestPayTypeEnum.WXPAY_H5);
        LOGGER.info("【微信支付】发起支付,入参:" + request.toString());
        PayResponse response = bestPayService.pay(request);
        LOGGER.info("【微信支付】发起支付,出参:" + response == null ? "" : response.toString());
        return response;
    }

    @Override
    public PayResponse notify(String notifyData) {
        // 1.验证签名
        // 2.支付状态
        // 3.支付金额
        // 4.支付人
        PayResponse payResponse = bestPayService.asyncNotify(notifyData);
        LOGGER.info("【微信支付】异步通知,出参:" + payResponse == null ? "" : JsonUtil.toJson(payResponse));

        // 查询订单
        String orderId = payResponse.getOrderId();
        OrderDTO orderDTO = orderService.findOne(orderId);

        // 判断订单是否存在
        if (orderDTO == null) {
            LOGGER.error("【微信支付】,异步通知,订单不存在,orderId={}", payResponse.getOrderId());
            throw new MallException(ResultEnum.ORDER_NOT_EXIST);
        }
        // 判断金额是否一致
        if (StringUtils.isEmpty(String.valueOf(orderDTO.getOrderAmount())) || StringUtils.isEmpty(String.valueOf(payResponse.getOrderAmount())) ||
                !MathUtil.equals(orderDTO.getOrderAmount().doubleValue(), payResponse.getOrderAmount())) {
            LOGGER.error("【微信支付】,异步通知,订单金额不一致,orderId={},微信通知金额={},系统金额={}",
                    payResponse.getOrderId(),
                    payResponse.getOrderAmount(),
                    orderDTO.getOrderAmount());
            throw new MallException(ResultEnum.WXPAY_NOTIFY_MONEY_VERIFY_ERROR);
        }
        // 修改订单的支付状态
        OrderDTO paid = orderService.paid(orderDTO);
        return payResponse;
    }

    /**
     * 微信退款
     * @param orderDTO
     * @return
     */
    @Override
    public RefundResponse refund(OrderDTO orderDTO) {
        RefundRequest refundRequest = new RefundRequest();
        refundRequest.setOrderId(orderDTO.getOrderId());
        refundRequest.setOrderAmount(orderDTO.getOrderAmount().doubleValue());
        refundRequest.setPayTypeEnum(BestPayTypeEnum.WXPAY_H5);
        LOGGER.info("【微信退款】入参:{}", refundRequest.toString());
        RefundResponse refundResponse = bestPayService.refund(refundRequest);
        LOGGER.info("【微信退款】出参:{}", refundResponse == null?"":refundResponse.toString());
        return refundResponse;
    }
}
